import PySimpleGUI as sg
import pandas as pd

from .event_handler import EventHandler
from common.config import T,get_index_codes, get_global_index_codes, get_config_path
from datetime import datetime
#sg.theme_previewer()
sg.theme('Default1')

class MainWindow:
    def __init__(self):
        layout = self.__init_layout()
        self.window = sg.Window('AI量化投资系统', layout, size=(680,600),font=('微软雅黑', 9), default_element_size=(50, 1),grab_anywhere=False)
        self.event_handler = EventHandler(self.window)


    def __init_layout(self):
        menu_def = [['文件',['打开Config目录']],
                    ['数据', ['更新指数','dump csv到qlib格式']],
                    ['关于', '关于软件...'], ]

        tab_bkt_layout = self.__init_bkt_layout()
        etf_layout = self.__init_etf_layout()

        layout = [
            [sg.Menu(menu_def, tearoff=True)],
            [sg.TabGroup([[sg.Tab('AI量化回测', tab_bkt_layout),
                           sg.Tab('ETF分析', etf_layout)]])],
        ]
        return layout

    def __init_bkt_layout(self):
        choices = tuple(list(T.get_task_list().keys()))
        benchs = get_index_codes() + list(get_global_index_codes().keys())

        table = sg.Table(values=[['------------','--------','--------','--------','--------','--------','--------']],
                          headings=['策略名称','累计收益','年化收益','夏普比','最大回撤','年化收益与最大回撤比','波动率'],
                          #max_col_width=800,
                          #size=(800,30),
                          def_col_width=100,
                          auto_size_columns=True,  # 自动调整列宽（根据上面第一次的values默认值为准，update时不会调整）
                          #display_row_numbers=True,  # 序号
                          justification='center',  # 字符排列 left right center
                          num_rows=6,  # 行数
                          #row_height=20,  # 行高
                          key='-RATIO-',
                          selected_row_colors=('white','grey'),
                          #font=('微软雅黑', 12),
                          #text_color='black',
                          #background_color='white',
                          enable_events=True,
                          #bind_return_key=True
                          )


        return [
            [sg.Text('任务列表：')],
            [sg.Combo(choices, size=(50, 20), key='-TASKS-', enable_events=True)],
            [sg.Button('编辑任务'), sg.Button('运行任务')],
            [sg.Text('回测结果分析：')],
            [sg.Listbox(tuple(T.get_task_list()), key='-RESULTS-', select_mode=sg.LISTBOX_SELECT_MODE_MULTIPLE,
                        size=(20, 10)),
             sg.Listbox(tuple(benchs), key='-BENCH-', select_mode=sg.LISTBOX_SELECT_MODE_MULTIPLE, size=(20, 10)),
             sg.Button('分析')],
            [sg.Text('起始日期：'),
             sg.InputText('20100101', size=(12, 1), key='-START-'),
             sg.Text('结束日期：'),
             sg.InputText(datetime.now().strftime('%Y%m%d'), size=(12, 1), key='-END-')],
            [table],
            [sg.Multiline(default_text='系统运行状态...', key='-OUT-', size=(80, 6))]
             ]

    def __init_etf_layout(self):
        etfs = get_config_path()+'/etf_top.csv'
        etf_basic = get_config_path()+'/etf.csv'
        df_basic = pd.read_csv(etf_basic)
        df_basic.index = df_basic['ts_code']

        df = pd.read_csv(etfs)
        values = []
        for index, row in df.iterrows():
            basic = df_basic.loc[row['instrument']]
            values.append([row['instrument'],basic['name'],basic['benchmark'],basic['fund_type'],basic['list_date'],row['$close / Ref($close, 20) - 1']])

        return [[sg.T('请输入查询条件：')],
                [sg.In(key='-QUERY-')],
                [sg.Button('查询')],
                [sg.Table(values=values,
                          headings=['代码', '名称','基准', '类型', '成立时间','20日动量'],
                          #max_col_width=800,
                          size=(800,200),
                          def_col_width=100,
                          #auto_size_columns=True,  # 自动调整列宽（根据上面第一次的values默认值为准，update时不会调整）
                          #display_row_numbers=True,  # 序号
                          justification='center',  # 字符排列 left right center
                          #num_rows=20,  # 行数
                          #row_height=20,  # 行高
                          key='_table_',
                          selected_row_colors=('white','grey'),
                          #font=('微软雅黑', 12),
                          #text_color='black',
                          #background_color='white',
                          enable_events=True,
                          #bind_return_key=True
                          )
                          ],
                ]

    def show(self):
        while True:
            event, values = self.window.Read()
            if event == None or event == sg.WIN_CLOSED:
                break
            self.event_handler.process(event, values)
        self.close()


    def close(self):
        self.window.Close()


